import { getImage, getPage } from '../../utils/config';
import api from '../../utils/api';
import { extend, http, storage, $toast, urlEncode } from '../../utils/utils';
import wxApi from '../../utils/wxApi';
const app = getApp();

Page({

    /**
     * 页面的初始数据
     */
    data: {
        getImage: getImage,
        getPage: getPage,
        loading: 0,
        colList: [],
        colCats: [],
        tabsActive: 0,
        tabsId: 0,
        filterId: 1,
        filterType: 0,
        matrixType: 0,
        filterSwicth: 0,
        productsType: [],
        typeActive: [],
        goodsList: [],
        pageIndex: 1,
        pages: 0,
        orders: 'desc',
        filterAttr: '',
        abnor: false,
        loadmore: false,
        loaddone: false,
    },

    /**
     * 当前点击分类
     */
    tabsClick(e) {
        const id = this.data.colCats[e.detail.index];

        //赋值当前分类
        this.setData({
            tabsId: id,
            goodsList: [],
            pageIndex: 1,
            loadmore: false,
            loaddone: false,
            loading: 0,
        });

        //页面返回顶部
        wx.pageScrollTo({
            scrollTop: 0
        },0)

        //更新商品数据
        this.httpGetGoods(() => {
            this.setData({
                loading: 1
            })
        }, false);
    },

    /**
     * 切换风格
     */
    tabsMatrixTap (){
        let type;
        this.data.matrixType === 0 ? type = 1 : type = 0;
        this.setData({
            matrixType: type
        })
    },

    /**
     * 筛选产品
     */
    tabsFilterTap (e){
        const id = e.currentTarget.dataset.id || e.target.dataset.id;
        let type, typeText;
        if (id == 3){
            switch (this.data.filterType){
                case 0:
                    type = 1
                    typeText = 'asc'
                break;
                case 1:
                    type = 2
                    typeText = 'desc'
                break;
                case 2:
                    type = 1
                    typeText = 'asc'
                break;
            }

            this.setData({
                filterType: type,
                orders: typeText,
            })
        }else{
            this.setData({
                filterType: 0,
                orders: 'desc',
            })
        }

        this.setData({
            filterId: id,
            goodsList: [],
            pageIndex: 1,
            pages: 0,
            loadmore: false,
            loaddone: false,
            loading: 0,
        })

        //更新商品数据
        this.httpGetGoods(() => {
            this.setData({
                loading: 1
            })
        }, false);
    },

    /**
     * filter隐藏显示控制
     */
    filterSwitchTap (e){
        let type;
        this.data.filterSwicth === 0 ? type = 1 : type = 0;
        this.setData({
            filterSwicth: type
        })
    },

    /**
     * 获取筛选项
     */
    filterBtn (e){
        const data = e.target.dataset || e.currentTarget.dataset;
        const productsType = this.data.productsType;
        const typeActive = this.data.typeActive;
        const _length = typeActive.length;

        if(productsType.length){
            productsType[data.parentsId].list.forEach((item,index) => {
                
                //如果点击的id等于循环到的id则高亮
                if (index === data.id){

                    //判断是否存在且已选择过
                    if (item['active'] && item['active'] === 1){ //已选择
                        item['active'] = 0;

                        for (let i = 0; i <= _length - 1; i++) {
                            if (typeActive[i]['attr_id'] === item['attr_id']) {
                                typeActive.splice(i, 1);
                                break;
                            }
                        }
                    }else{ //未选择
                        item['active'] = 1;
                        if (_length){
                            for (let i = 0; i <= _length - 1; i++ ){
                                if (typeActive[i]['attr_id'] === item['attr_id']){
                                    typeActive.splice(i, 1);
                                    typeActive.push(item);
                                    break;
                                } else if (i === _length - 1){
                                    typeActive.push(item);
                                    break;
                                }
                            }
                        }else{
                            typeActive.push(item);
                        }
                    }
                }else{
                    //不等直接取消高亮
                    item['active'] = 0;
                }
            })
            console.log(typeActive);
            this.setData({
                productsType: productsType,
                typeActive: typeActive,
            })
        }
    },

    /**
     * 重置筛选 
     */
    filterReset (){
        const productsType = this.data.productsType;
        productsType.forEach((item) => {
            item.list.forEach((item) => {
                item['active'] = 0
            })
        })
        this.setData({
            productsType: productsType,
            typeActive: [],
            filterAttr: '',
        })
    },

    /**
     * 提交筛选
     */
    filterSubmit (){
        this.setData({
            filterAttr: JSON.stringify(this.data.typeActive),
            goodsList: [],
            pageIndex: 1,
            pages: 0,
            loadmore: false,
            loaddone: false,
            filterSwicth: 0,
            loading: 0,
        });

        //更新商品数据
        this.httpGetGoods(() => {
            this.setData({
                loading: 1
            })
        }, false);
    },

    /**
     * 请求数据
     */
    httpGetGoods (callback, loadStyle = true){
        // //获取商品
        http.post(api.default, {
            data: {
                action: 'GetProducts',
                cid: this.data.tabsId,
                keyword: '',
                pagesize: 20,
                isrecommend: 0,
                filter_attr: this.data.filterAttr,
                pageindex: this.data.pageIndex,
                ordersid: this.data.filterId,
                orders: this.data.orders,
            }
        }, loadStyle).then(res => {
            const goodsData = res.data.data;
            const newGoodsData = [].concat(this.data.goodsList, goodsData.list);
            this.setData({
                loaddone: this.data.pageIndex === goodsData.pages ? true : false,
                abnor: newGoodsData.length ? false : true,
                goodsList: newGoodsData,
                pages: goodsData.pages,
            })
        }).finally(() => {
            callback && callback();
        })
    },

    /**
     * 跳转商品页
     */
    pageGoodsTap(e) {
        const data = e.currentTarget.dataset || e.target.dataset;
        if(data.id){
            wxApi.navigateTo(getPage.goods, {
                id: data.id
            })
        }
    },

    /**
     * 监听页面滚动
     */
    onPageScroll() {
        
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        //获取分类
        http.get(api.default,{
            data: {
                action: 'getcategorylist',
                id: options.id,
            }
        }, false).then(res => {
            const colData = res.data.data.list[0];
            let colCats = [];
            colData.list.forEach((item) =>{
                colCats.push(item.ColId);
            });

            //更改页面标题
            wx.setNavigationBarTitle({
                title: colData.ColTitle
            })

            //获取筛选数据
            http.get(api.default, {
                data: {
                    action: 'getproductstype',
                    cid: options.id,
                }
            }, false).then(res => {
                this.setData({
                    productsType: res.data.data,
                })
            })

            //赋值分类
            this.setData({
                tabsId: options.id,
                colList: colData.list,
                colCats: colCats,
                tabsActive: colCats.indexOf(Number(options.id)),
            });

            //首次获取商品
            this.httpGetGoods(() => {
                this.setData({
                    loading: 1
                })
            }, false);
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        //未请求完且未在加载中
        if(!this.data.loaddone && !this.data.loadmore) {
            //显示加载效果
            wx.showNavigationBarLoading();
            this.setData({
                loadmore: true
            })
            //统计页数
            const pages = this.data.pages;
            let pagesCount = this.data.pageIndex;
            if (pagesCount < pages) {
                //请求页码
                pagesCount++;
                this.setData({
                    pageIndex: pagesCount,
                })
                //加载数据
                this.httpGetGoods(() => {
                    //不管结果如何关闭导航栏加载效果
                    wx.hideNavigationBarLoading();
                    this.setData({
                        loadmore: false
                    })
                },false);
            } else {
                //关闭加载效果
                wx.hideNavigationBarLoading();
                this.setData({
                    loadmore: false,
                    loaddone: true,
                })
            }
        }
    }
})